/**
 * Created by Administrator on 2018/9/20.
 */
+function ($) {
    'use strict';

    var EditTable = function (f, e) {
        this.$element = $(f);
        this.options = $.extend({}, EditTable.DEFAULTS, e);
        this.init()
    };

    EditTable.DEFAULTS = {
        minLength:1,
        showLineNumber:false,
        rowFormElementsExpr: ":input[type='text'], :input[type='password']," +
        " :input[type='radio'], :input[type='checkbox'], :input[type='file'],:input[type='hidden'], select , textarea"
    };

    EditTable.prototype.init = function () {
        this.initTable();
        this.initBody();
    }
    EditTable.prototype.initTable = function () {
        var that = this,
            $el = this.$element,
            options = this.options,
            $body = $el.children("tbody"),
            header= $el.find(" > thead > tr");
        if(options.showLineNumber){
            header.prepend("<th>序号</th>");
        }
        header.prepend('<th><button type="button" ' +
            'class="btn btn-xs btn-circle yellow btn-row-add" title="添加新行项"' +
            ' style="padding: 0px 8px;margin-right: 5px"> ' +
            ' <i class="fa fa-plus"></i>  ' +
            '</button></th>');

        header.children("th").each(function (n) {
            var th = $(this);
            th.attr("data-index", n)
        });

        header.find(".btn-row-add").on("click", function () {
            var row = $('<tr class="dynamic-edit-row">' + that.templateRowHTML + "</tr>"),   k = that.existRowCount;
            $body.append(row);
            if(options.showLineNumber){
                that.showLineNumber();
            }
            row.find('input').each(function () {
                var input = $(this);
                console.log(input.attr('name'))
                that.resetInputAttrNameIndex(input, "name",k);
            });
            that.existRowCount ++
            Bolt.runComponents( Bolt.eventType.afterAjaxPageShow, row);
        });

    }

    EditTable.prototype.initBody = function () {
        var that = this,
            $body =  this.$element.children("tbody"),
            options = this.options,
            $tr = $body.children("tr"),
            removeBnt = '<button type="button" class="btn btn-xs btn-circle default btn-row-remove"' +
                ' title="删除当前行项" style="padding: 0px 8px;margin-right: 5px"> ' +
                ' <i class="fa fa-minus"></i>  </button>';
        $tr.each(function (index) {
            var row = $(this);
            row.addClass("dynamic-edit-row");
            if(options.showLineNumber){
                row.prepend('<td class="row-num" style="min-width: 50px;padding-top: 17px;text-align: center">' +
                    '<span class="row-num">' + (index + 1) + "</span></td>");
            }
            row.prepend('<td class="row-operations" style="min-width: 30px;padding-top: 17px;">' + removeBnt + "</td>");
        });
        this.existRowCount = $tr.length;
        if(options.showLineNumber){
            that.showLineNumber();
        }
        var lastRow = this.$element.find(" > tbody > tr:last");
        lastRow.children("td").each(function (index) {
            var td = $(this);
            td.addClass("dynamic-edit-row-cell");
            td.attr("data-index", index)
        });
        this.templateRowHTML = lastRow.html();
        console.log(this.templateRowHTML);
        if (options.minLength == undefined || $tr.size() > 1) {
            lastRow.remove()
        }
        this.$element.on("click", ".btn-row-remove", function (q) {
            var bnt = $(q.target);
            var tr = bnt.closest("tr");
            if (options.minLength) {
                if ($body.children("tr:visible").size() == options.minLength) {
                    alert("至少需要保留 " + options.minLength + " 条行项数据");
                    return
                }
            }
            tr.remove()
            if(options.showLineNumber){
                that.showLineNumber();
            }
        });
    }

    EditTable.prototype.showLineNumber = function () {
        var that = this,
            $el = this.$element,
            $body = $el.children("tbody"),
            $tr = $body.children("tr"),
            index = 1;
        $tr.each(function (m) {
            var tr = $(this);
            if (tr.is(":visible")) {
                tr.find("span.row-num").html((index++))
            }
        })
    };

    EditTable.prototype.resetInputAttrNameIndex = function (g, f, e) {
        var h = g.attr(f);
        if (h && h.indexOf("[")!= -1) {
            var i = h.substring(0, h.indexOf("[") + 1) + e + h.substring(h.indexOf("]"), h.length);
            g.attr(f, i)
        }
    };

    EditTable.prototype.allData = function(){
        var that = this,datas=[],  options = this.options,
            $body =  that.$element.children("tbody"),
            $trs = $body.find(">tr");
        $trs.each(function(i) {
            var  $tr = $(this), data={};
            $tr.find(options.rowFormElementsExpr).each(function () {
                var $input = $(this), name = $input.attr('name'),value;
                if($input.data("extSwitch")){
                    value = $input.bootstrapSwitch("state");
                }else{
                    value = $input.val();
                }
                data[name] = value;
            })
            datas.push(data);
        })
        return datas;
    }

    EditTable.prototype.load = function (data) {
        var that = this,
            $body =  this.$element.children("tbody"),
            options = this.options;
        if (!$.isArray(data)) {
            return;
        }
        var trFragments = $(document.createDocumentFragment());
        for(var i=0;i<data.length;i++){
            var row = $('<tr class="dynamic-edit-row">' + that.templateRowHTML + "</tr>"),   k = that.existRowCount;
            row.find(options.rowFormElementsExpr).each(function () {
                var input = $(this),name = input.attr('name');
                input.attr("value", Bolt.getAccessor(data[i],name));
                that.resetInputAttrNameIndex(input, "name",k);
            });
            Bolt.runComponents(Bolt.eventType.afterAjaxPageShow, row);
            trFragments.append(row);
            that.existRowCount ++

        }
        if(options.showLineNumber){
            that.showLineNumber();
        }
        $body.html(trFragments);
    };


    function Plugin(option) {
        var property = option,value,
            args = Array.prototype.slice.call(arguments, 1);
        this.each(function () {
            var $this   = $(this),
                data = $this.data("editTable");
            var options = typeof property == "object" && property;
            if (!data) {
                $this.data("editTable", (data = new EditTable(this, options)))
            }
            if (typeof property == "string") {
                value =  data[property].apply(data,args);
            }
        })
        return typeof value === 'undefined' ? this : value;
    }

    $.fn.editTable = Plugin
    $.fn.editTable.Constructor = EditTable;
    $.fn.editTable.defaults = EditTable.DEFAULTS;

    $(document).on(Bolt.eventType.initUI, function(e) {
        $(e.target).find('table[data-toggle="editTable"]').each(function() {
            var $this = $(this), options = $this.data()
            if (!$this.length) return
            if (options.options && typeof options.options === 'string') options.options = options.options.toObj()
            $.extend(options, typeof options.options === 'object' && options.options)
            Plugin.call($this, options)
        })
    })

    Bolt.addComponent({
        name: "editTable",
        plugin: Plugin,
        runPoint: Bolt.eventType.afterAjaxPageShow,
        expr: "table[data-toggle='editTable']",
        order: 2000
    })

}(jQuery);
